<template>
  <div>
    <a-modal
      title="导出"
      :visible="showDownload"
      @ok="handleOk"
      :footer="null"
      @cancel="() => { step = 0, showDownload = false }">
      <div style="display: flex;align-items:center;flex-direction: column;">
        <p>总行数:{{ total }}，每张表{{ pageRows }}行，共{{ allTotal }}个表</p>
        <a-spin v-show="step != 100" />
        <a-progress :percent="step" />
        <p v-show="step == 100" style="font-size: 20px;font-weight: 600;margin: 20px 0;">完成！</p>
      </div>
    </a-modal>
  </div>
</template>
<script>
export default {
  data () {
    return {
      showDownload: false, // 控制是否显示弹窗
      step: 0, // 步骤
      pageRows: 10000, // 下载一页条数
      fileName: '', // 文件名称
      param: {}, // 下载参数
      url: '', // 下载链接
      allTotal: 0,
      total: 0
    }
  },
  methods: {
    handleOk(){},
    openForm ({ pageRows, total, url, param, fileName }) {
      if (pageRows) {
        this.pageRows = pageRows
      }
      if (total || total == 0) {
        this.total = total
      } else {
        this.$message.error('缺少总条数')
      }
      if (url) {
        this.url = url
      } else {
        this.$message.error('缺少下载链接')
      }
      if (param) {
        this.param = param
      }
      if (fileName) {
        this.fileName = fileName
      } else {
        this.$message.error('缺少下载文件名称')
      }

      this.download()
    },
    async download () {
      this.showDownload = true
      this.step = 0
      const count = Math.ceil(this.total / this.pageRows)
      const step = Math.ceil(100 / count)
      this.allTotal = count
      for (let i = 1; i <= count; i++) {
        await this.downloadDetails(i)
        // this.step = step * i
      }
      // this.step = 100
    },
    sumStep () {
      const count = Math.ceil(this.total / this.pageRows)
      const step = Math.ceil(100 / count)
      this.step = Math.ceil((this.step / step + 1) * step)
      if (this.step > 100) {
        this.step = 100
      }
    },
    async downloadDetails (PageIndex) {
      await this.$http.post(this.url, {
        PageIndex: PageIndex,
        PageRows: this.pageRows,
        ...this.param
      }, { responseType: 'blob' }).then(res => {
        const url = URL.createObjectURL(res)
        const aTag = document.createElement('a')
        aTag.download = this.fileName
        aTag.href = url
        aTag.click()
        URL.revokeObjectURL(aTag.href)
        this.sumStep()
      }).catch(err => {
        this.$message.error(err)
      })
    }
  }
}
</script>
